package cn.nkpro.elcube.cloud;

import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Map;

@Activate(group = CommonConstants.CONSUMER)
public class NkCloudConsumerFilter implements Filter {

    @Setter
    private Map<String,Object> cloudProviderAuths;

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        if(cloudProviderAuths!=null){
            String groupId = StringUtils.substringBefore(invocation.getTargetServiceUniqueName(),"/");
            Object o = cloudProviderAuths.get(groupId);
            if(o instanceof Map){
                RpcServiceContext context = RpcContext.getServiceContext();
                context.setAttachment("Authentication-Key",((Map) o).get("username"));
                context.setAttachment("Authentication-Secret",((Map) o).get("password"));
            }else if(o!=null){
                RpcContext.getServiceContext().setAttachment("Authentication", SecurityContextHolder.getContext().getAuthentication());
            }
        }

        try{
            return invoker.invoke(invocation);
        }finally {
            RpcContext.removeContext();
        }
    }
}
